<template>
  <el-dialog
    :title="isEdit ? '编辑机柜' : '添加机柜'"
    v-model="dialogVisible"
    width="800px"
    :close-on-click-modal="false"
    align-center
    :modal-class="'cabinet-form-dialog'"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="right"
      class="cabinet-form"
      status-icon
    >
      <div class="form-row">
        <el-form-item label="机柜名称" prop="cabinet_name">
          <template #label><span>机柜名称</span></template>
          <el-input v-model="form.cabinet_name" placeholder="请输入机柜名称" />
        </el-form-item>

        <el-form-item label="位置" prop="location">
          <template #label><span>位置</span></template>
          <el-input v-model="form.location" placeholder="请输入位置，如：A区-01" />
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="所在机房" prop="room_id" class="full-width">
          <template #label><span>所在机房</span></template>
          <el-select v-model="form.room_id" placeholder="请选择机房" disabled>
            <el-option :value="currentRoom.room_id" :label="currentRoom.room_name" />
          </el-select>
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="机柜高度/U" prop="rack_units" class="number-input">
          <template #label><span>机柜高度(U)</span></template>
          <el-input-number
            v-model="form.rack_units"
            :min="1"
            :max="52"
            :controls="false"
            :precision="0"
          />
        </el-form-item>

        <el-form-item label="承重/kg" prop="weight_capacity" class="number-input">
          <template #label><span>承重(kg)</span></template>
          <el-input-number
            v-model="form.weight_capacity"
            :min="0"
            :step="100"
            :controls="false"
            :precision="0"
          />
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="网络端口数/个" prop="network_ports" class="number-input">
          <template #label><span>网络端口数(个)</span></template>
          <el-input-number
            v-model="form.network_ports"
            :min="0"
            :step="2"
            :controls="false"
            :precision="0"
          />
        </el-form-item>

        <el-form-item label="额定功率/w" prop="power_capacity" class="number-input">
          <template #label><span>额定功率(W)</span></template>
          <el-input-number
            v-model="form.power_capacity"
            :min="0"
            :step="100"
            :controls="false"
            :precision="0"
          />
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="制造商" prop="manufacturer">
          <template #label><span>制造商</span></template>
          <el-input v-model="form.manufacturer" placeholder="请输入制造商" />
        </el-form-item>

        <el-form-item label="型号" prop="model">
          <template #label><span>型号</span></template>
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="序列号" prop="serial_number">
          <template #label><span>序列号</span></template>
          <el-input v-model="form.serial_number" placeholder="请输入序列号" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <template #label><span>状态</span></template>
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="正常" value="正常" />
            <el-option label="维护中" value="维护中" />
            <el-option label="故障" value="故障" />
          </el-select>
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="PDU" prop="power_distribution_unit">
          <template #label><span>PDU</span></template>
          <el-input v-model="form.power_distribution_unit" placeholder="请输入PDU信息" />
        </el-form-item>

        <el-form-item label="交换机" prop="network_switch">
          <template #label><span>交换机</span></template>
          <el-input v-model="form.network_switch" placeholder="请输入交换机信息" />
        </el-form-item>
      </div>

      <el-form-item label="备注" prop="notes">
        <template #label><span>备注</span></template>
        <el-input v-model="form.notes" type="textarea" :rows="3" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoomConfigStore } from '@/store/roomConfigStore'
import { assetService } from '@/api/assetService'

const props = defineProps<{
  visible: boolean
  cabinetData?: never
}>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  success: []
}>()

const roomConfigStore = useRoomConfigStore()
const currentRoom = computed(() => roomConfigStore.currentRoom!)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const isEdit = computed(() => !!props.cabinetData)

// 表单数据
const form = reactive({
  cabinet_name: '',
  room_id: currentRoom.value?.room_id,
  location: '',
  rack_units: 42,
  power_capacity: 5000,
  network_ports: 48,
  weight_capacity: 1000,
  manufacturer: '',
  model: '',
  serial_number: '',
  power_distribution_unit: '',
  network_switch: '',
  status: '正常',
  notes: '',
})

// 表单验证规则
const rules: FormRules = {
  cabinet_name: [{ required: true, message: '请输入机柜名称', trigger: 'blur' }],
  location: [{ required: true, message: '请输入位置', trigger: 'blur' }],
  rack_units: [{ required: true, message: '请输入机柜高度', trigger: 'change' }],
  power_capacity: [{ required: true, message: '请输入额定功率', trigger: 'change' }],
  network_ports: [{ required: true, message: '请输入网络端口数', trigger: 'change' }],
  manufacturer: [{ required: true, message: '请输入制造商', trigger: 'blur' }],
  model: [{ required: true, message: '请输入型号', trigger: 'blur' }],
  serial_number: [{ required: true, message: '请输入序列号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      const submitData = {
        ...form,
        available_units: form.rack_units, // 初始可用U数等于总U数
        power_available: form.power_capacity, // 初始可用功率等于额定功率
        available_network_ports: form.network_ports, // 初始可用端口数等于总端口数
      }
      if (isEdit.value && props.cabinetData) {
        await assetService.updateCabinet(submitData)
        ElMessage.success('更新成功')
      } else {
        await assetService.createCabinet(submitData)
        ElMessage.success('添加成功')
      }
      emit('success')
      dialogVisible.value = false
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : '操作失败'
      console.error(isEdit.value ? '更新机柜失败:' : '添加机柜失败:', err)
      ElMessage.error(errorMsg)
    } finally {
      loading.value = false
    }
  })
}

// 关闭对话框
const handleClose = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    cabinet_name: '',
    room_id: currentRoom.value?.room_id,
    location: '',
    rack_units: 42,
    power_capacity: 5000,
    network_ports: 48,
    weight_capacity: 1000,
    manufacturer: '',
    model: '',
    serial_number: '',
    power_distribution_unit: '',
    network_switch: '',
    status: '正常',
    notes: '',
  })
}

// 监听编辑数据变化
watch(
  () => props.cabinetData,
  (newData) => {
    if (newData) {
      Object.assign(form, newData)
    }
  },
  { immediate: true },
)

// 监听当前机房变化，自动设置机房ID
watch(
  () => currentRoom.value,
  (newRoom) => {
    if (newRoom) {
      form.room_id = newRoom.room_id
    }
  },
  { immediate: true },
)
</script>

<style scoped lang="scss">
.cabinet-form {
  padding: 0 20px;
  margin: 0 auto;
  max-width: 800px;

  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 16px;

    .el-form-item {
      flex: 1;
      margin-bottom: 0;
      min-width: 0;

      &:last-child {
        margin-bottom: 0;
      }

      :deep(.el-form-item__label) {
        padding-right: 12px;
        font-weight: normal;
        color: var(--el-text-color-regular);
        white-space: nowrap;
        display: flex;
        align-items: center;

        &::before {
          content: '';
          flex: 0 0 auto;
          width: 8px;
        }

        span {
          flex: 1;
          text-align: justify;
          text-align-last: justify;
          letter-spacing: 1px;
        }

        &::after {
          content: ':';
          flex: 0 0 auto;
          width: 8px;
          text-align: center;
        }
      }

      :deep(.el-form-item__content) {
        flex: 1;
        min-width: 0;
        margin-left: 0 !important;
      }

      :deep(.el-input__wrapper),
      :deep(.el-select),
      :deep(.el-textarea__wrapper) {
        width: 100%;
        box-shadow: 0 0 0 1px var(--el-border-color) inset;

        &:hover {
          box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
        }

        &.is-focus {
          box-shadow: 0 0 0 1px var(--el-color-primary) inset;
        }
      }

      :deep(.number-input) {
        width: 100%;

        .el-input__wrapper {
          padding-right: 11px;
          height: 32px;
          line-height: 32px;
          background: none;
        }

        .el-input__inner {
          text-align: left;
          padding-right: 0;
          height: 32px;
          line-height: 32px;
          background: none;
        }

        .el-input-number__decrease,
        .el-input-number__increase {
          display: none;
        }

        .el-input__wrapper {
          padding: 0 11px;
          box-shadow: 0 0 0 1px var(--el-border-color) inset;

          &:hover {
            box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
          }

          &.is-focus {
            box-shadow: 0 0 0 1px var(--el-color-primary) inset;
          }
        }
      }
    }
  }
}

.dialog-footer {
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  border-top: 1px solid var(--el-border-color-lighter);

  :deep(.el-button) {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 8px 20px;
    height: 32px;

    span {
      line-height: 1;
    }
  }
}
</style>
